﻿using Serilog.Core;
using Serilog.Events;
using System.Diagnostics;

namespace VideoTools.Help
{
    public class LogCallerEnricher : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var skip = 3;
            while (true)
            {
                var stack = new StackFrame(skip);
                if (!stack.HasMethod())
                {
                    logEvent.AddPropertyIfAbsent(new LogEventProperty("Caller", new ScalarValue("<unknown method>")));
                    return;
                }

                var method = stack.GetMethod();
                if (method.DeclaringType != null &&
                    !method.DeclaringType.Assembly.FullName.Contains("Serilog") &&
                    !method.DeclaringType.Assembly.FullName.Contains("System"))
                {
                    var caller = $"{method.DeclaringType.FullName}.{method.Name}";
                    var lineNumber = stack.GetFileLineNumber();

                    logEvent.AddPropertyIfAbsent(new LogEventProperty("Caller", new ScalarValue(caller)));
                    logEvent.AddPropertyIfAbsent(new LogEventProperty("LineNumber", new ScalarValue(lineNumber)));
                    return;
                }

                skip++;
            }
        }
    }
}
